{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "所有的链接\n",
      "a http://example.com/elsie Elsie\n",
      "a http://example.com/lacie Lacie\n",
      "a http://example.com/tillie Tillie\n",
      "获取特定的URL地址\n",
      "a http://example.com/elsie [u'sister'] Elsie\n",
      "正则表达式匹配\n",
      "a http://example.com/tillie [u'sister'] Tillie\n",
      "获取P段落的文字\n",
      "p [u'story'] Once upon a time there were three little sisters; and their names were\n",
      "Elsie,\n",
      "Lacie and\n",
      "Tillie;\n",
      "and they lived at the bottom of a well.\n"
     ]
    }
   ],
   "source": [
    "#! /usr/bin/python\n",
    "# -*- coding:UTF-8 -*-\n",
    "\n",
    "import re\n",
    "\n",
    "from bs4 import BeautifulSoup\n",
    "html_doc = \"\"\"\n",
    "<html><head><title>The Dormouse's story</title></head>\n",
    "<body>\n",
    "<p class=\"title\"><b>The Dormouse's story</b></p>\n",
    "<p class=\"story\">Once upon a time there were three little sisters; and their names were\n",
    "<a href=\"http://example.com/elsie\" class=\"sister\" id=\"link1\">Elsie</a>,\n",
    "<a href=\"http://example.com/lacie\" class=\"sister\" id=\"link2\">Lacie</a> and\n",
    "<a href=\"http://example.com/tillie\" class=\"sister\" id=\"link3\">Tillie</a>;\n",
    "and they lived at the bottom of a well.</p>\n",
    "<p class=\"story\">...</p>\n",
    "\"\"\"\n",
    "\n",
    "#创建一个BeautifulSoup解析对象\n",
    "soup = BeautifulSoup(html_doc,\"html.parser\",from_encoding=\"utf-8\")\n",
    "#获取所有的链接\n",
    "links = soup.find_all(\"a\")\n",
    "print \"所有的链接\"\n",
    "for link in links:\n",
    "    print link.name,link['href'],link.get_text()\n",
    "    \n",
    "print \"获取特定的URL地址\"\n",
    "link_node = soup.find('a',href=\"http://example.com/elsie\")\n",
    "print link_node.name,link_node['href'],link_node['class'],link_node.get_text()\n",
    "\n",
    "print \"正则表达式匹配\"\n",
    "link_node = soup.find('a',href=re.compile(r\"ti\"))\n",
    "print link_node.name,link_node['href'],link_node['class'],link_node.get_text()\n",
    "\n",
    "print \"获取P段落的文字\"\n",
    "p_node = soup.find('p',class_='story')\n",
    "print p_node.name,p_node['class'],p_node.get_text()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
